<template>
  <div class="wrap">
    <div v-if="!loaded">
      <div>
      <div id="dataLoading" v-loading="!loaded" :element-loading-text="$t('message.SoundInsulationMaterialTool.loading') + loadedPercent + $t('message.SoundInsulationMaterialTool.loadedPercent')"
           :style="{width: '100%', height: 100 + 'px'}">
        <iframe v-show="loaded" id="dialogPluginIframe"
                :style="{width: '100%', height: 100 + 'px'}"></iframe>
      </div>
    </div>
    </div>
    <div v-else class="border materialAttributeMessageBox" tabindex="-1">
      <sound-insulation-material-info-content :assembly-tree-material-attribute-info-list="resultAssemblyTreeMaterialAttributeInfoList"
                                              :is-mass-re-computed="isMassReComputed"
                                              :is-mass-computed="isMassComputed"
                                              :is-export-data="isExportData"
      />
    </div>
    <div class="btn">
      <el-button type="primary"
                 size="small"
                 :disabled="componenState"
                 @click="exportData">{{ $t('message.SoundInsulationMaterialTool.export') }}
      </el-button>
      <el-button size="small"
                 @click="cancel">{{ $t('message.SoundInsulationMaterialTool.close') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import {soundInsulationMaterialCommand} from "../../../command/SoundInsulationMaterialCommand";
import SoundInsulationMaterialInfoContent from "./SoundInsulationMaterialInfoContent.vue";
import DialogMixin from "../DialogMixin";
import {MaterialNumberType, materialClassMap, materialSpecificationMap} from "../SoundInsulationMaterialTool/MaterialNumberType";

export default {
  mixins: [DialogMixin],
  name: "SoundInsulationMaterialTool",
  components: {SoundInsulationMaterialInfoContent},
  data() {
    return {
      assemblyTree: null,//装配树
      currentAssemblyTreeList: [],
      assemblyTreeMaterialAttributeInfoList: [],
      resultAssemblyTreeMaterialAttributeInfoList: [],
      protoRefInfoList: [],
      materialNumberList: [],
      isExportData: true,
      workspaceMode: '',
      isInit: false,
      componenState: false,
      loaded: true,
      loadedPercent: 0,
    }
  },
  methods: {
    async initAssemblyTree() {
      if (this.workspaceMode === 'PartDocument') {
        //do nothing
      } else if (this.workspaceMode === 'AssemblyDocument') {
        this.loaded = false;
        this.loadedPercent = 0;
        this.componenState = true;
        this.currentAssemblyTreeList = this.assemblyTree;
        await this.traverseAssemblyTree(this.currentAssemblyTreeList);
        this.calculateArea();
        this.resultAssemblyTreeMaterialAttributeInfoList = this.assemblyTreeMaterialAttributeInfoList;
        this.componenState = false;
        this.loaded = true;
      }
    },
    async traverseAssemblyTree(instanceList) {
      if (instanceList === 0 || !instanceList) {
        return;
      }
      for (let i = 0; i < instanceList.length; i++) {
        let instanceId = instanceList[i].id;
        let instanceName = instanceList[i].name;
        //按proto归类零件
        let data = await soundInsulationMaterialCommand.getInstanceProtoRefByInstanceId(instanceId);
        if(instanceList === this.assemblyTree) {
          this.loadedPercent = Math.floor((i / this.assemblyTree.length) * 100);
        }
        if (data) {
          let protoRefId = data.protoRefId;
          let protoRefDocId = data.protoRefDocId;
          let protoRefVersionId = data.protoRefVersionId;
          let protoRefName = data.protoRefName;
          let protoRefType = data.protoRefType;
          if (!(protoRefType === "part") || protoRefName === "") {
            await this.traverseAssemblyTree(instanceList[i].children);
            continue;
          }
          let protoRefIndex = this.protoRefInfoList.findIndex(item => item.protoRefDocId === protoRefDocId);
          if (protoRefIndex === -1) {
            let protoRefInfo = {
              protoRefId: protoRefId,
              protoRefDocId: protoRefDocId,
              protoRefVersionId: protoRefVersionId,
              protoRefName: protoRefName,
              protoRefType: protoRefType
            };
            this.protoRefInfoList.push(protoRefInfo);
          } else {
            await this.traverseAssemblyTree(instanceList[i].children);
            continue;
          }
          //(零件)原型名拆分
          let docIdIndex = protoRefName.indexOf(protoRefDocId);
          let partNumber = protoRefName;
          if (docIdIndex !== -1) {
            partNumber = partNumber.substr(0, docIdIndex - 1);
          }
          let config = {
            documentId: protoRefDocId,
            versionId: protoRefVersionId,
            isTopDownEdit: false,
            socketMsg: ""
          }
          let res = await soundInsulationMaterialCommand.getDocVersionAttribute(config);
          if(res) {
            if (res?.manifestItems) {
              let manifestItems = res?.manifestItems;
              let indexMaterial = manifestItems.findIndex(item => item.name === "材料");
              if (indexMaterial !== -1) {
                let material = manifestItems[indexMaterial];
                let value = material.value;
                let matList = [];
                while (value !== '') {
                  let sepIndex = value.indexOf(';');
                  if(sepIndex !== -1) {
                    let strMat = value.substr(0, sepIndex);
                    matList.push(strMat);
                    let length = value.length;
                    value = value.substr(sepIndex + 1, length - sepIndex - 1);
                  } else {
                    let strMat = value;
                    matList.push(strMat);
                    value = "";
                  }
                }
                for (let matIndex = 0; matIndex < matList.length; matIndex++) {
                  let matNumberIndex = matList[matIndex].indexOf('|');
                  let materialNumber = matList[matIndex].substr(0, matNumberIndex);
                  let materialSize = matList[matIndex].substr(matNumberIndex + 1);
                  let materialClass = "";
                  let materialSpecification = "";

                  let isMaterial = true;
                  switch (materialNumber) {
                    case MaterialNumberType.N00000134:
                    case MaterialNumberType.N00000137:
                    case MaterialNumberType.N00000139:
                    case MaterialNumberType.N00000148:
                    case MaterialNumberType.N00000149:
                    case MaterialNumberType.N00000153:
                      break;
                    default:
                      isMaterial = false;
                      break;
                  }
                  if (isMaterial) {
                    let materialNumberIndex = this.assemblyTreeMaterialAttributeInfoList.findIndex(item => item.materialNumber === materialNumber);
                    let mapIndex = this.findIndexByValue(MaterialNumberType, materialNumber);
                    if (mapIndex !== -1) {
                      materialClass = materialClassMap[mapIndex];
                      materialSpecification = materialSpecificationMap[mapIndex];
                    }
                    let materialInfo = {
                      partNumber: partNumber,
                      materialNumber: materialNumber,
                      class: materialClass,
                      materialSpecification: materialSpecification,
                      materialSize: materialSize,
                      area: ""
                    }
                    this.assemblyTreeMaterialAttributeInfoList.push(materialInfo);
                  } else {
                    await this.traverseAssemblyTree(instanceList[i].children);
                  }
                }
              }
            }
          }
        }
      }
      if(instanceList === this.assemblyTree) {
        this.loadedPercent = 100;
      }
    },
    calculateArea() {
      for(let i = 0; i < this.assemblyTreeMaterialAttributeInfoList.length; i++) {
        let material = this.assemblyTreeMaterialAttributeInfoList[i];
        let materialNumber = material.materialNumber;
        let materialSize = material.materialSize;
        let leftPIndex = materialSize.indexOf('(');
        let layer = 1;
        let thickness = "";
        let length = "";
        let width = "";
        let unit = "mm";
        if(leftPIndex === -1) {
          let mIndex = materialSize.indexOf("mm");
          if(mIndex !== -1) {
            length = materialSize.substr(0, mIndex);
            width = length;
            unit = materialSize.substr(mIndex, materialSize.length - mIndex);
          }
        } else {
          let tempStr = materialSize;
          let lIndex = tempStr.indexOf("层");
          layer = tempStr.substr(0, lIndex);
          let dIndex = tempStr.indexOf('δ');
          //Length × Width)
          if(dIndex !== -1) {
            let sIndex = tempStr.indexOf('″');
            thickness = tempStr.substr(dIndex + 1, sIndex - dIndex - 1);
            let mulIndex = tempStr.indexOf('×');
            tempStr = tempStr.substr(mulIndex + 1);
          } else {
            let lPIndex = tempStr.indexOf('(');
            tempStr = tempStr.substr(lPIndex + 1);
          }
          let mmIndex1 = tempStr.indexOf("mm");
          length = tempStr.substr(0, mmIndex1);
          let multIndex = tempStr.indexOf('×');
          tempStr = tempStr.substr(multIndex + 1);
          let mmIndex2 = tempStr.indexOf("mm");
          width = tempStr.substr(0, mmIndex2);
        }
        let sizeInfo = {
          layer: layer,
          thickness: thickness,
	        length: length,
	        width: width,
	        unit: unit
        }
        let sizeIndex = this.materialNumberList.findIndex(item => item.materialNumber === materialNumber);
        if(sizeIndex === -1) {
          let sizeInfoList = [];
          sizeInfoList.push(sizeInfo);
          let materialNumberInfo = {
            materialNumber: materialNumber,
            materialFirstIndex: i,
            sizeInfoList: sizeInfoList
          }
          this.materialNumberList.push(materialNumberInfo);
        } else {
          this.materialNumberList[sizeIndex].sizeInfoList.push(sizeInfo);
        }
        console.log("MaterialNumberList: " + this.materialNumberList);
      }

      this.materialNumberList.forEach( item => {
        let firstIndex = item.materialFirstIndex;
        let sizeList = item.sizeInfoList;
        let area = 0;
        sizeList.forEach(size => {
          let layer = parseFloat(size.layer);
          let l = parseFloat(size.length);
          let w = parseFloat(size.width);
          area += layer * l * w ;
        });
        this.assemblyTreeMaterialAttributeInfoList[firstIndex].area = area;
      });

    },
    exportData() {
      this.isExportData = -this.isExportData;
    },
    changePluginContainerHeight() {
      soundInsulationMaterialCommand.changePluginContainerHeight({
        minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight, width: 880,
      });
    },
    findIndexByValue(obj, value) {
      let index = -1;
      Object.keys(obj).forEach((key, idx) => {
        if (obj[key] === value) {
          index = idx;
        }
      });
      return index;
    },
    cancel() {
      soundInsulationMaterialCommand.closeActiveCmd();
    }
  },
  created() {
    if (!this.isInit){
      this.isComputed = false;
      soundInsulationMaterialCommand.init(1200, 500, 550, () => {
        soundInsulationMaterialCommand.clearAllHighLight();
        this.isInit = true;
        if (this.workspaceMode.length === 0) {
          let params = [];
          soundInsulationMaterialCommand.getWorkspaceMode(params, async (data) => {
            this.workspaceMode = data;
            let instance = await soundInsulationMaterialCommand.getInstanceTree();
            if (instance) {
              this.assemblyTree = instance;
              await this.initAssemblyTree();
            }
          });
        }
        this.changePluginContainerHeight();
      });
    }
  },
}
</script>

<style scoped>
.wrap {
    font-size: 12px;
}
</style>
